<?php

namespace App\Http\Controllers\Admin\Finance\Payable;

use App\Exports\PayableTakeOrderDetailExport;
use App\Exports\ReceivableTakeOrderDetailExport;
use App\Http\Controllers\Admin\Base\ExchangeRate;
use App\Http\Controllers\Controller;
use App\Http\Requests\airline\base\BanRequest;
use App\Models\airline\base\FlightModel as BaseFlightModel;
use App\Models\DictionaryModel;
use App\Models\finance\PayableTakeOrderDetailModel;
use App\Models\finance\PayableTakeOrderModel;
use App\Models\finance\PayableTmpModel;
use App\Models\finance\ReceivableTakeOrderDetailModel;
use App\Models\OrderModel;
use App\Models\PayBillModel;
use App\Models\TakeOrderModel;
use App\Models\TakeOrderRecModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class TakeOrderDetail extends Controller
{
    use BanRequest;

    /**
     * Notes:列表
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $take_order_sn = $request->input('take_order_sn', '');
        $name = $request->input('name', '');
        $agent_id = $request->input('agent_id', '');
        $currency_id = $request->input('currency_id', '');
        $flight_date_start = $request->input('flight_date_start', '');
        $flight_date_end = $request->input('flight_date_end', '');
        $route_id = $request->input('route_id', '');
        $pay_status = $request->input('pay_status', '');


        $query = PayableTakeOrderDetailModel::query()->with(['agent', 'currency', 'take_order']);

        if($take_order_sn){
            $query->whereHas('take_order', function($query) use ($take_order_sn) {
                $query->where('sn', 'like', '%' . $take_order_sn . '%');
            });
        }

        if($name){
            $query->where('name', 'like', "%{$name}%");
        }

        if($agent_id){
            $query->where('agent_id', $agent_id);
        }

        if($currency_id){
            $query->where('currency_id', $currency_id);
        }

        if($route_id){
            $query->whereHas('take_order', function($query) use ($route_id) {
                $query->where('route_id', $route_id);
            });
        }

        if($pay_status){
            $query->where('pay_status', $pay_status);
        }

        if($flight_date_start && $flight_date_end){
            $query->whereBetween('flight_date', [$flight_date_start, $flight_date_end]);
        }

        $total_amount = $query->sum('amount') ?? 0;
        $total_amount_cny = $query->sum('amount_cny') ?? 0;
        $items = $query
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {

            $res = [
                'id' => $item->id,
                'flight_date' => $item->flight_date,
                'sn' => $item->take_order->sn ?? '',
                'agent_name' => $item->agent->name ?? '',
                'name' => $item->name,
                'number' => $item->number,
                'unit' => $item->unit,
                'price' => $item->price,
                'currency_code' => $item->currency->short_code ?? '',
                'rate' => $item->rate,
                'amount' => $item->amount,
                'amount_cny' => $item->amount_cny,
                'type' => 'data'
            ];
            return $res;
        });
        $list = $list->toArray();
        $list = $this->groupBy($list, 'sn');


        $data = [];
        foreach ($list as $key => $value) {
            $amount = $amount_cny = 0;
            foreach ($value as $key2 => $value2) {
                $amount += $value2['amount'];
                $amount_cny += $value2['amount_cny'];
                $data[] = $value2;
            }
            $data[] = [
                'id' => 0,
                'flight_date' => '',
                'sn' => '',
                'agent_name' => '',
                'name' => '',
                'number' => '',
                'unit' => '',
                'price' => '',
                'currency_code' => '',
                'rate' => '单票小计',
                'amount' => round($amount, 2),
                'amount_cny' => round($amount_cny, 2),
                'type' => 'total'
            ];
        }

        $statistics = [
            'amount' => $total_amount,
            'amount_cny' => $total_amount_cny,
        ];

        return $this->success(['list' => $data, 'statistics' => $statistics]);
    }

    public function groupBy($array, $key) {
        return array_reduce($array, function ($result, $item) use ($key) {
            $groupKey = $item[$key];
            if (!isset($result[$groupKey])) {
                $result[$groupKey] = [];
            }
            $result[$groupKey][] = $item;
            return $result;
        }, []);
    }
    public function list_old(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $take_order_sn = $request->input('take_order_sn', '');
        $name = $request->input('name', '');
        $agent_id = $request->input('agent_id', '');
        $currency_id = $request->input('currency_id', '');
        $flight_date_start = $request->input('flight_date_start', '');
        $flight_date_end = $request->input('flight_date_end', '');
        $route_id = $request->input('route_id', '');
        $pay_status = $request->input('pay_status', '');


        $query = PayableTakeOrderDetailModel::query()->with(['agent', 'currency', 'take_order']);

        if($take_order_sn){
            $query->whereHas('take_order', function($query) use ($take_order_sn) {
                $query->where('sn', 'like', '%' . $take_order_sn . '%');
            });
        }

        if($name){
            $query->where('name', 'like', "%{$name}%");
        }

        if($agent_id){
            $query->where('agent_id', $agent_id);
        }

        if($currency_id){
            $query->where('currency_id', $currency_id);
        }

        if($route_id){
            $query->whereHas('take_order', function($query) use ($route_id) {
                $query->where('route_id', $route_id);
            });
        }

        if($pay_status){
            $query->where('pay_status', $pay_status);
        }

        if($flight_date_start && $flight_date_end){
            $query->whereBetween('flight_date', [$flight_date_start, $flight_date_end]);
        }


        $total = $query->count('id');
        $total_amount = $query->sum('amount') ?? 0;
        $total_amount_cny = $query->sum('amount_cny') ?? 0;
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {

            $res = [
                'id' => $item->id,
                'flight_date' => $item->flight_date,
                'sn' => $item->take_order->sn ?? '',
                'agent_name' => $item->agent->name ?? '',
                'name' => $item->name,
                'number' => $item->number,
                'unit' => $item->unit,
                'price' => $item->price,
                'currency_code' => $item->currency->short_code ?? '',
                'rate' => $item->rate,
                'amount' => $item->amount,
                'amount_cny' => $item->amount_cny,
            ];
            return $res;
        });

        $statistics = [
            'amount' => $total_amount,
            'amount_cny' => $total_amount_cny,
        ];

        return $this->success(['list' => $list, 'total' => $total, 'statistics' => $statistics]);
    }


    public function bill_create(Request $request) {
        $take_order_sn = $request->input('take_order_sn', '');
        $name = $request->input('name', '');
        $agent_id = $request->input('agent_id', '');
        $currency_id = $request->input('currency_id', '');
        $flight_date_start = $request->input('flight_date_start', '');
        $flight_date_end = $request->input('flight_date_end', '');
        $route_id = $request->input('route_id', '');

        $query = PayableTakeOrderDetailModel::query()->with(['agent', 'currency', 'take_order']);

        if($take_order_sn){
            $find = TakeOrderModel::query()->where('sn', $take_order_sn)->first();
            $take_order_id = $find->id ?? 0;
            $query->where('take_order_id', $take_order_id);
        }

        if($name){
            $query->where('name', 'like', "%{$name}%");
        }

        if($agent_id){
            $query->where('agent_id', $agent_id);
        }

        if($currency_id){
            $query->where('currency_id', $currency_id);
        }

        if($route_id){
            $query->whereHas('take_order', function($query) use ($route_id) {
                $query->where('route_id', $route_id);
            });
        }

        if($flight_date_start && $flight_date_end){
            $query->whereBetween('flight_date', [$flight_date_start, $flight_date_end]);
        }

        $list = $query->where('bill_id', '>', 0)->get();
        if(count($list) > 0){
            return $this->error('有明细已生成过账单');
        }

        $list = $query->get();

        $agent_id = $list->pluck('agent_id')->unique()->toArray();
        if(count($agent_id) > 1){
            return $this->error('请选择同一个供应商');
        }

        $amount = $list->sum('amount_cny');

        $bill = new PayBillModel();
        $bill->agent_id = $agent_id[0];
        $bill->sn = getCode('pay_bill', 'EML', 4);
        $bill->amount = $amount;
        $bill->start = $flight_date_start;
        $bill->end = $flight_date_end;
        $bill->save();

        $list->update([
            'bill_id' => $bill->id,
        ]);

        return $this->success();
    }



    public function export(Request $request) {
        $ids = $request->input('ids',  []);
        $details = PayableTakeOrderDetailModel::with(['agent', 'currency', 'take_order'])->whereIn('id', $ids)->get();

        if(!$details){
            return $this->error('请选择要导出的数据');
        }


        $list = $details->map(function($item) {

            $res = [
                'flight_date' => $item->flight_date,
                'sn' => $item->take_order->sn ?? '',
                'agent_name' => $item->agent->name ?? '',
                'name' => $item->name,
                'number' => $item->number,
                'unit' => $item->unit,
                'price' => $item->price,
                'currency_code' => $item->currency->short_code ?? '',
                'rate' => $item->rate,
                'amount' => $item->amount,
                'amount_cny' => $item->amount_cny,
            ];
            return $res;
        });

        $file_name = '应付明细-'.date('Ymd').'.xlsx';

        return Excel::download(new PayableTakeOrderDetailExport($list), $file_name);

    }




}
